from django.contrib.syndication.feeds import Feed
from best_buy_book.shop.models import Libro
from django.utils.feedgenerator import SyndicationFeed
from django.utils.xmlutils import SimplerXMLGenerator

# Modificar sites en admin para dejarlo como http://www.a3b.com, en lugar de
# example.com
class BookFeed(SyndicationFeed):
    mime_type = 'application/xml'
    ns = u"http://www.a3b.com/2008/Book"
     
    def write(self, outfile, encoding):
        handler = SimplerXMLGenerator(outfile, encoding)
        handler.startDocument()
        handler.startElement(u'libros', self.root_attributes())
        self.add_root_elements(handler)
        self.write_items(handler)
        handler.endElement(u"libros")

    def root_attributes(self):
        if self.feed['language'] is not None:
            return {u"xmlns": self.ns, u"xml:lang": self.feed['language']}
        else:
            return {u"xmlns": self.ns}

    def add_root_elements(self, handler):
        handler.addQuickElement(u"title", self.feed['title'])
        handler.addQuickElement(u"link", "", {u"rel": u"alternate", u"href": self.feed['link']})
        
        """
        if self.feed['feed_url'] is not None:
            handler.addQuickElement(u"link", "", {u"rel": u"self", u"href": self.feed['feed_url']})
        handler.addQuickElement(u"id", self.feed['id'])
        #handler.addQuickElement(u"updated", rfc3339_date(self.latest_post_date()).decode('utf-8'))
        if self.feed['author_name'] is not None:
            handler.startElement(u"author", {})
            handler.addQuickElement(u"name", self.feed['author_name'])
            if self.feed['author_email'] is not None:
                handler.addQuickElement(u"email", self.feed['author_email'])
            if self.feed['author_link'] is not None:
                handler.addQuickElement(u"uri", self.feed['author_link'])
            handler.endElement(u"author")
        if self.feed['subtitle'] is not None:
            handler.addQuickElement(u"subtitle", self.feed['subtitle'])
        for cat in self.feed['categories']:
            handler.addQuickElement(u"category", "", {u"term": cat})
        if self.feed['feed_copyright'] is not None:
            handler.addQuickElement(u"rights", self.feed['feed_copyright'])
        """

    def write_items(self, handler):
        for item in self.items:
            handler.startElement(u"book", self.item_attributes(item))
            self.add_item_elements(handler, item)
            handler.endElement(u"book")

    def add_item_elements(self, handler, item):
        handler.addQuickElement(u"titulo", item['title'])
        
        handler.addQuickElement(u"keyword", '1000')
        
        """
        handler.addQuickElement(u"link", u"", {u"href": item['link'], u"rel": u"alternate"})
        if item['pubdate'] is not None:
            handler.addQuickElement(u"updated", rfc3339_date(item['pubdate']).decode('utf-8'))
        """
        
        """
        # Author information.
        if item['author_name'] is not None:
            handler.startElement(u"author", {})
            handler.addQuickElement(u"name", item['author_name'])
            if item['author_email'] is not None:
                handler.addQuickElement(u"email", item['author_email'])
            if item['author_link'] is not None:
                handler.addQuickElement(u"uri", item['author_link'])
            handler.endElement(u"author")

        # Unique ID.
        if item['unique_id'] is not None:
            unique_id = item['unique_id']
        else:
            unique_id = get_tag_uri(item['link'], item['pubdate'])
        handler.addQuickElement(u"url", unique_id)

        # Summary.
        if item['description'] is not None:
            handler.addQuickElement(u"summary", item['description'], {u"type": u"html"})

        # Enclosure.
        if item['enclosure'] is not None:
            handler.addQuickElement(u"link", '',
                {u"rel": u"enclosure",
                 u"href": item['enclosure'].url,
                 u"length": item['enclosure'].length,
                 u"type": item['enclosure'].mime_type})

        # Categories.
        for cat in item['categories']:
            handler.addQuickElement(u"category", u"", {u"term": cat})

        # Keywords.
        #for word in item['keyword']:
        #    handler.addQuickElement(u"keyword", u"", {u"word": cat})
        #if item['keyword'] is not None:
        #    handler.startElement(u"keyword", {})
        #    handler.addQuickElement(u"word", item['keyword'])
            #if item['author_email'] is not None:
            #    handler.addQuickElement(u"email", item['author_email'])
            #if item['author_link'] is not None:
            #    handler.addQuickElement(u"uri", item['author_link'])
        #    handler.endElement(u"author")


        # Rights.
        if item['item_copyright'] is not None:
            handler.addQuickElement(u"rights", item['item_copyright'])
        """

class A3B(Feed):
    feed_type = BookFeed#Atom1Feed
    title = "Almost Best Buy Book"
    link = "/shop/feed/buscar/"
    description = "Busqueda de libros que no se encuentran en Best Buy Book."
    def items(self):
        return Libro.objects.all()#order_by('-pub_date')[:5]
    
"""
<libros xmlns="http://www.a3b.com/2008/Book" xml:lang="es-mx">
    <title>Almost Best Buy Book</title>
    <link href="http://example.com/shop/feed/buscar/" rel="alternate"></link>
    <entry>
        <title>Otro libro</title>
        <link href="http://example.com/shop/libro/1234567890" rel="alternate">
        </link>
        <id>http://example.com/shop/libro/1234567890</id>
        <summary type="html">Otro libro</summary>
    </entry>
    <entry>
        <title>fsfsweewwert</title>
        <link href="http://example.com/shop/libro/5555555555" rel="alternate"></link>
        <id>http://example.com/shop/libro/5555555555</id>
        <summary type="html">fsfsweewwert</summary>
    </entry>
</libros>
"""